package com.bwie.policy;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.bwie.pojo.TbPacketRecord;
import com.bwie.pojo.TbPolicy;
import com.bwie.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.Date;

public class MultiRedPacketPolicy implements IRedPolicy{


    private TbPolicy tbPolicy;
    private Integer userId;

    private KafkaTemplate kafkaTemplate;

    private StringRedisTemplate redisTemplate;

    public MultiRedPacketPolicy(TbPolicy tbPolicy,Integer userId,KafkaTemplate kafkaTemplate,StringRedisTemplate redisTemplate){
        System.out.println("多次触发策略");
        this.tbPolicy=tbPolicy;
        this.userId=userId;
        this.kafkaTemplate=kafkaTemplate;
        this.redisTemplate=redisTemplate;
    }
    @Override
    public Result execute() {

        String key="red-"+tbPolicy.getPolicyId()+"-"+userId;

        Boolean hasKey = redisTemplate.hasKey(key);
        if (!hasKey){
            redisTemplate.opsForValue().set(key, String.valueOf(tbPolicy.getTopLimit()));
        }

        Long decrement = redisTemplate.opsForValue().decrement(key);

        if (decrement<0){
            return Result.error().setMsg("红包次数已经抢完了");
        }

        long time = new Date().getTime();
        if (time<tbPolicy.getBeginTime().getTime()){
            return Result.error().setMsg("红包活动未开始");
        }
        if (time>tbPolicy.getEndTime().getTime()){
            return Result.error().setMsg("红包活动已经结束");
        }


        double amount = RandomUtil.randomDouble(0.01, tbPolicy.getPacketAmount());


        TbPacketRecord tbPacketRecord = new TbPacketRecord();
        tbPacketRecord.setPolicyId(tbPolicy.getPolicyId());
        tbPacketRecord.setPacketAmount(amount);
        tbPacketRecord.setUserId(userId);

        //消息不重复
        long nextId = IdUtil.getSnowflake(1, 1).nextId();
        tbPacketRecord.setMsgId(nextId);
        redisTemplate.opsForValue().set("msg-"+nextId,"1");


        String message= JSON.toJSONString(tbPacketRecord);
        kafkaTemplate.send("topic-packet",message);



        return Result.ok().setData(amount);
    }
}
